<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书籍管理系统</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script src="./js/jquery-3.7.1.js"></script>
    <style>
        /* 添加页面样式 */
        #addBookForm {
            display: none; /* 默认隐藏 */
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1000; /* 确保在其他内容之上 */
            width: 400px;
            padding: 20px;
            background-color: #ffffff;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
        }

        .form-group {
            margin-bottom: 15px;
        }

        /* 添加遮罩层样式 */
        #overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            height: 100vh;
            width: 100vw;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }
    </style>

</head>
<body>
<div class="container-fluid">
    <!-- tou 标题 -->
    <div class="row">
        <div class="col-md-12">
            <h1 class="text-center">书籍管理系统</h1>
        </div>
    </div>
    <!-- search 搜索-->
    <div class="row">
        <div class="form-row col-md-8">
            <div class="col">
                <input type="text" id="bookName" class="form-control" placeholder="书籍名称">
            </div>
            <div class="col">
                <input type="text" id="author" class="form-control" placeholder="作者">
            </div>
        </div>
        <div class="col-md-4">
            <button type="button" class="btn btn-primary">搜索</button>
            <script>
                $(function () {
                    const $bookNameInput = $('#bookName');
                    const $authorInput = $('#author');

                    $('button').click(function () {
                        const $btn = $(this);
                        if ($btn.data('loading')) return;
                        $btn.data('loading', true);

                        const bookName = $bookNameInput.val();
                        const author = $authorInput.val();

                        const requestUrl = `http://localhost:8080/books?bookName=${bookName}&author=${author}`;
                        $.ajax({
                            url: requestUrl,
                            type: 'get',
                            dataType: 'json',
                            success: function (res) {
                                console.log('返回的数据:', res);
                                $('tbody').empty();
                                var books = res.data;
                                books.forEach(function (book) {
                                    var tr = '<tr>' +
                                        '<th scope="row">' + book.bookID + '</th>' +
                                        '<td>' + book.bookName + '</td>' +
                                        '<td>' + book.author + '</td>' +
                                        '<td>' + book.money + '</td>' +
                                        '<td>' +
                                        '<button type="button" class="btn btn-primary">修改</button>' +
                                        '<button type="button" class="btn btn-danger">删除</button>' +
                                        '</td>' +
                                        '</tr>';
                                    $('tbody').append(tr);
                                });
                            },
                            error: function (xhr, status, error) {
                                console.error('请求失败:', error);
                                alert('请求失败，请稍后再试');
                            },
                            complete: function () {
                                $btn.data('loading', false); // 重置按钮状态
                            }
                        });
                    });
                });
            </script>

            <button type="button" class="btn btn-primary" id="addBookBtn">添加</button>

            <!-- 添加表单模态框 -->
            <div id="overlay"></div>
            <div id="addBookForm">
                <h3>添加新书籍</h3>
                <div class="form-group">
                    <label for="newBookName">书名:</label>
                    <input type="text" id="newBookName" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="newAuthor">作者:</label>
                    <input type="text" id="newAuthor" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="newMoney">价格:</label>
                    <input type="number" id="newMoney" class="form-control" required>
                </div>
                <div class="form-group">
                    <button type="button" class="btn btn-success">提交</button>
                    <button type="button" class="btn btn-secondary" id="cancelAdd">取消</button>
                </div>
            </div>

            <script>
                $(function () {
                    // 显示添加表单
                    $('#addBookBtn').click(function () {
                        $('#overlay').show();
                        $('#addBookForm').show();
                        $(document).ready(function () {
                            $('#addBookForm h3').text('添加新书籍');
                        });
                    });

                    // 隐藏添加表单（点击取消按钮或遮罩层）
                    $('#cancelAdd, #overlay').click(function () {
                        $('#overlay').hide();
                        $('#addBookForm').hide();
                    });

                    $('#addBookForm button').click(function () {
                        let bookName = $('#newBookName').val();
                        let author = $('#newAuthor').val();
                        let money = $('#newMoney').val();
                        console.log(bookName, author, money)
                        $.ajax({
                            url: 'http://localhost:8080/books',
                            type: 'Post',
                            contentType: 'application/json', // 设置内容类型
                            dataType: 'json',
                            data: JSON.stringify({ // 将对象序列化为 JSON 字符串
                                bookName: bookName,
                                author: author,
                                money: money
                            }),
                            success: function (res) {

                                console.log('书籍添加成功:', res);
                                alert('书籍添加成功');

                                // 清空表单并隐藏
                                $('#addBookForm').trigger('reset').hide();

                                // 刷新表格数据
                                location.reload();
                            }
                        });
                    });
                });
            </script>
        </div>
    </div>
    <!-- table 表格 -->
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover">
                <thead>
                <tr>
                    <th scope="col">编号</th>
                    <th scope="col">书名</th>
                    <th scope="col">作者</th>
                    <th scope="col">价格</th>
                    <th scope="col">操作</th>
                </tr>
                </thead>
                <tbody>
                <script>
                    $(function () {
                        $.ajax({
                            url: 'http://localhost:8080/books',
                            type: 'get',
                            dataType: 'json',
                            success: function (res) {
                                console.log('返回的数据:', res);
                                var books = res.data;
                                books.forEach(function (book) {
                                    var tr = '<tr>' +
                                        '<th scope="row">' + book.bookID + '</th>' +
                                        '<td>' + book.bookName + '</td>' +
                                        '<td>' + book.author + '</td>' +
                                        '<td>' + book.money + '</td>' +
                                        '<td>' +
                                        '<button type="button" class="btn btn-primary">修改</button>' +
                                        '<button type="button" class="btn btn-danger">删除</button>' +
                                        '</td>' +
                                        '</tr>';
                                    $('tbody').append(tr);
                                });
                            }
                        })
                    })
                </script>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
<script>
    $(function () {
        // 删除书籍功能
        $('tbody').on('click', '.btn-danger', function () {
            const $btn = $(this);
            if ($btn.data('loading')) return;
            $btn.data('loading', true);

            const bookId = $btn.closest('tr').find('th').text();
            if (!confirm(`确定要删除编号为 ${bookId} 的书籍吗？`)) {
                $btn.data('loading', false);
                return;
            }

            $.ajax({
                url: `http://localhost:8080/books/${bookId}`,
                type: 'delete',
                dataType: 'json',
                success: function (res) {
                    console.log('删除响应:', res);
                    if (res.code === 1) {
                        alert('书籍删除成功');
                        // 刷新表格数据
                        location.reload();
                    } else {
                        alert(res.message || '删除失败');
                    }
                },
                error: function (xhr, status, error) {
                    console.error('删除请求失败:', error);
                    alert('书籍删除失败，请稍后再试');
                },
                complete: function () {
                    $btn.data('loading', false);
                }
            });
        });
    });

    $(function () {
    $(document).ready(function () {
        $('#addBookForm h3').text('修改书籍');
    });

    $('#cancelAdd, #overlay').click(function () {
        $('#overlay').hide();
        $('#addBookForm').hide();
    });

    $('tbody').on('click', '.btn-primary', function () {
        const $btn = $(this);
        if ($btn.data('loading')) return;
        $btn.data('loading', true);

        const $row = $btn.closest('tr');
        const bookId = $row.find('th').text().trim(); // 获取 bookID
        const bookName = $row.find('td:eq(0)').text().trim(); // 第一列是书名
        const author = $row.find('td:eq(1)').text().trim();   // 第二列是作者
        const money = $row.find('td:eq(2)').text().trim();    // 第三列是价格


        $('#newBookName').val(bookName);
        $('#newAuthor').val(author);
        $('#newMoney').val(money);

        $('#addBookForm').data('bookId', bookId);


        $('#overlay').show();
        $('#addBookForm').show();


        $('#addBookForm button').off('click').on('click', function () {
            let updatedBookName = $('#newBookName').val();
            let updatedAuthor = $('#newAuthor').val();
            let updatedMoney = $('#newMoney').val();
            let updatedBookId = $('#addBookForm').data('bookId'); // 获取 bookID


            if (!updatedBookName || !updatedAuthor || !updatedMoney) {
                alert('请填写所有字段');
                return;
            }

            $.ajax({
                url: 'http://localhost:8080/books',
                type: 'put',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    bookID: updatedBookId,
                    bookName: updatedBookName,
                    author: updatedAuthor,
                    money: updatedMoney
                }),
                success: function (res) {
                    console.log('书籍修改成功:', res);

                    $('#addBookForm').trigger('reset').hide();
                    location.reload();
                },
                error: function (xhr, status, error) {
                    console.error('书籍修改失败:', error);
                    alert('书籍修改失败，请稍后再试');
                },
                complete: function () {
                    $btn.data('loading', false);
                }
            });
        });
    });
});


</script>
</html>